home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Python / pythonrun.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  24.9 KB  |  1,169 lines

  1. /* Python interpreter top-level routines, including init/exit */
  2.  
  3. #include "Python.h"
  4.  
  5. #include "grammar.h"
  6. #include "node.h"
  7. #include "parsetok.h"
  8. #include "errcode.h"
  9. #include "compile.h"
  10. #include "eval.h"
  11. #include "marshal.h"
  12. #include "protos/pythonrun.h"
  13.  
  14. #ifdef HAVE_UNISTD_H
  15. #include <unistd.h>
  16. #endif
  17.  
  18. #ifdef HAVE_SIGNAL_H
  19. #include <signal.h>
  20. #endif
  21.  
  22. #ifdef MS_WIN32
  23. #undef BYTE
  24. #include "windows.h"
  25. #endif
  26.  
  27. extern char *Py_GetPath();
  28.  
  29. extern grammar _PyParser_Grammar; /* From graminit.c */
  30.  
  31. /* Forward */
  32. static void initmain Py_PROTO((void));
  33. static void initsite Py_PROTO((void));
  34. static PyObject *run_err_node Py_PROTO((node *n, char *filename,
  35.                    PyObject *globals, PyObject *locals));
  36. static PyObject *run_node Py_PROTO((node *n, char *filename,
  37.                    PyObject *globals, PyObject *locals));
  38. static PyObject *run_pyc_file Py_PROTO((FILE *fp, char *filename,
  39.                    PyObject *globals, PyObject *locals));
  40. static void err_input Py_PROTO((perrdetail *));
  41. static void initsigs Py_PROTO((void));
  42. static void call_sys_exitfunc Py_PROTO((void));
  43. static void call_ll_exitfuncs Py_PROTO((void));
  44.  
  45. #ifdef Py_TRACE_REFS
  46. int _Py_AskYesNo(char *prompt);
  47. #endif
  48.  
  49. extern void _PyUnicode_Init Py_PROTO((void));
  50. extern void _PyUnicode_Fini Py_PROTO((void));
  51. extern void _PyCodecRegistry_Init Py_PROTO((void));
  52. extern void _PyCodecRegistry_Fini Py_PROTO((void));
  53.  
  54.  
  55. int Py_DebugFlag; /* Needed by parser.c */
  56. int Py_VerboseFlag; /* Needed by import.c */
  57. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  58. int Py_NoSiteFlag; /* Suppress 'import site' */
  59. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
  60. int Py_FrozenFlag; /* Needed by getpath.c */
  61. int Py_UnicodeFlag = 0; /* Needed by compile.c */
  62.  
  63. static int initialized = 0;
  64.  
  65. /* API to access the initialized flag -- useful for eroteric use */
  66.  
  67. int
  68. Py_IsInitialized()
  69. {
  70.     return initialized;
  71. }
  72.  
  73. /* Global initializations.  Can be undone by Py_Finalize().  Don't
  74.    call this twice without an intervening Py_Finalize() call.  When
  75.    initializations fail, a fatal error is issued and the function does
  76.    not return.  On return, the first thread and interpreter state have
  77.    been created.
  78.  
  79.    Locking: you must hold the interpreter lock while calling this.
  80.    (If the lock has not yet been initialized, that's equivalent to
  81.    having the lock, but you cannot use multiple threads.)
  82.  
  83. */
  84.  
  85. void
  86. Py_Initialize()
  87. {
  88.     PyInterpreterState *interp;
  89.     PyThreadState *tstate;
  90.     PyObject *bimod, *sysmod;
  91.     char *p;
  92.  
  93.     if (initialized)
  94.         return;
  95.     initialized = 1;
  96.     
  97.     if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
  98.         Py_DebugFlag = 1;
  99.     if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
  100.         Py_VerboseFlag = 1;
  101.     if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
  102.         Py_OptimizeFlag = 1;
  103.  
  104.     interp = PyInterpreterState_New();
  105.     if (interp == NULL)
  106.         Py_FatalError("Py_Initialize: can't make first interpreter");
  107.  
  108.     tstate = PyThreadState_New(interp);
  109.     if (tstate == NULL)
  110.         Py_FatalError("Py_Initialize: can't make first thread");
  111.     (void) PyThreadState_Swap(tstate);
  112.  
  113.     interp->modules = PyDict_New();
  114.     if (interp->modules == NULL)
  115.         Py_FatalError("Py_Initialize: can't make modules dictionary");
  116.  
  117.     /* Init codec registry */
  118.     _PyCodecRegistry_Init();
  119.  
  120.     /* Init Unicode implementation; relies on the codec registry */
  121.     _PyUnicode_Init();
  122.  
  123.     _PyCompareState_Key = PyString_InternFromString("cmp_state");
  124.  
  125.     bimod = _PyBuiltin_Init_1();
  126.     if (bimod == NULL)
  127.         Py_FatalError("Py_Initialize: can't initialize __builtin__");
  128.     interp->builtins = PyModule_GetDict(bimod);
  129.     Py_INCREF(interp->builtins);
  130.  
  131.     sysmod = _PySys_Init();
  132.     if (sysmod == NULL)
  133.         Py_FatalError("Py_Initialize: can't initialize sys");
  134.     interp->sysdict = PyModule_GetDict(sysmod);
  135.     Py_INCREF(interp->sysdict);
  136.     _PyImport_FixupExtension("sys", "sys");
  137.     PySys_SetPath(Py_GetPath());
  138.     PyDict_SetItemString(interp->sysdict, "modules",
  139.                  interp->modules);
  140.  
  141.     _PyImport_Init();
  142.  
  143.     /* phase 2 of builtins */
  144.     _PyBuiltin_Init_2(interp->builtins);
  145.     _PyImport_FixupExtension("__builtin__", "__builtin__");
  146.  
  147.     initsigs(); /* Signal handling stuff, including initintr() */
  148.  
  149.     initmain(); /* Module __main__ */
  150.     if (!Py_NoSiteFlag)
  151.         initsite(); /* Module site */
  152. }
  153.  
  154. #ifdef COUNT_ALLOCS
  155. extern void dump_counts Py_PROTO((void));
  156. #endif
  157.  
  158. /* Undo the effect of Py_Initialize().
  159.  
  160.    Beware: if multiple interpreter and/or thread states exist, these
  161.    are not wiped out; only the current thread and interpreter state
  162.    are deleted.  But since everything else is deleted, those other
  163.    interpreter and thread states should no longer be used.
  164.  
  165.    (XXX We should do better, e.g. wipe out all interpreters and
  166.    threads.)
  167.  
  168.    Locking: as above.
  169.  
  170. */
  171.  
  172. void
  173. Py_Finalize()
  174. {
  175.     PyInterpreterState *interp;
  176.     PyThreadState *tstate;
  177.  
  178.     if (!initialized)
  179.         return;
  180.     initialized = 0;
  181.  
  182.     call_sys_exitfunc();
  183.  
  184.     /* Get current thread state and interpreter pointer */
  185.     tstate = PyThreadState_Get();
  186.     interp = tstate->interp;
  187.  
  188.     /* Disable signal handling */
  189.     PyOS_FiniInterrupts();
  190.  
  191.     /* Destroy PyExc_MemoryErrorInst */
  192.     _PyBuiltin_Fini_1();
  193.  
  194.     /* Cleanup Unicode implementation */
  195.     _PyUnicode_Fini();
  196.  
  197.     /* Cleanup Codec registry */
  198.     _PyCodecRegistry_Fini();
  199.  
  200.     /* Destroy all modules */
  201.     PyImport_Cleanup();
  202.  
  203.     /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  204.     _PyImport_Fini();
  205.  
  206.     /* Debugging stuff */
  207. #ifdef COUNT_ALLOCS
  208.     dump_counts();
  209. #endif
  210.  
  211. #ifdef Py_REF_DEBUG
  212.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  213. #endif
  214.  
  215. #ifdef Py_TRACE_REFS
  216.     if (
  217. #ifdef MS_WINDOWS /* Only ask on Windows if env var set */
  218.         getenv("PYTHONDUMPREFS") &&
  219. #endif /* MS_WINDOWS */
  220.         _Py_AskYesNo("Print left references?")) {
  221.         _Py_PrintReferences(stderr);
  222.     }
  223. #endif /* Py_TRACE_REFS */
  224.  
  225.     /* Delete current thread */
  226.     PyInterpreterState_Clear(interp);
  227.     PyThreadState_Swap(NULL);
  228.     PyInterpreterState_Delete(interp);
  229.  
  230.     /* Now we decref the exception classes.  After this point nothing
  231.        can raise an exception.  That's okay, because each Fini() method
  232.        below has been checked to make sure no exceptions are ever
  233.        raised.
  234.     */
  235.     _PyBuiltin_Fini_2();
  236.     PyMethod_Fini();
  237.     PyFrame_Fini();
  238.     PyCFunction_Fini();
  239.     PyTuple_Fini();
  240.     PyString_Fini();
  241.     PyInt_Fini();
  242.     PyFloat_Fini();
  243.  
  244.     /* XXX Still allocated:
  245.        - various static ad-hoc pointers to interned strings
  246.        - int and float free list blocks
  247.        - whatever various modules and libraries allocate
  248.     */
  249.  
  250.     PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  251.  
  252.     call_ll_exitfuncs();
  253.  
  254. #ifdef Py_TRACE_REFS
  255.     _Py_ResetReferences();
  256. #endif /* Py_TRACE_REFS */
  257. }
  258.  
  259. /* Create and initialize a new interpreter and thread, and return the
  260.    new thread.  This requires that Py_Initialize() has been called
  261.    first.
  262.  
  263.    Unsuccessful initialization yields a NULL pointer.  Note that *no*
  264.    exception information is available even in this case -- the
  265.    exception information is held in the thread, and there is no
  266.    thread.
  267.  
  268.    Locking: as above.
  269.  
  270. */
  271.  
  272. PyThreadState *
  273. Py_NewInterpreter()
  274. {
  275.     PyInterpreterState *interp;
  276.     PyThreadState *tstate, *save_tstate;
  277.     PyObject *bimod, *sysmod;
  278.  
  279.     if (!initialized)
  280.         Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  281.  
  282.     interp = PyInterpreterState_New();
  283.     if (interp == NULL)
  284.         return NULL;
  285.  
  286.     tstate = PyThreadState_New(interp);
  287.     if (tstate == NULL) {
  288.         PyInterpreterState_Delete(interp);
  289.         return NULL;
  290.     }
  291.  
  292.     save_tstate = PyThreadState_Swap(tstate);
  293.  
  294.     /* XXX The following is lax in error checking */
  295.  
  296.     interp->modules = PyDict_New();
  297.  
  298.     bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  299.     if (bimod != NULL) {
  300.         interp->builtins = PyModule_GetDict(bimod);
  301.         Py_INCREF(interp->builtins);
  302.     }
  303.     sysmod = _PyImport_FindExtension("sys", "sys");
  304.     if (bimod != NULL && sysmod != NULL) {
  305.         interp->sysdict = PyModule_GetDict(sysmod);
  306.         Py_INCREF(interp->sysdict);
  307.         PySys_SetPath(Py_GetPath());
  308.         PyDict_SetItemString(interp->sysdict, "modules",
  309.                      interp->modules);
  310.         initmain();
  311.         if (!Py_NoSiteFlag)
  312.             initsite();
  313.     }
  314.  
  315.     if (!PyErr_Occurred())
  316.         return tstate;
  317.  
  318.     /* Oops, it didn't work.  Undo it all. */
  319.  
  320.     PyErr_Print();
  321.     PyThreadState_Clear(tstate);
  322.     PyThreadState_Swap(save_tstate);
  323.     PyThreadState_Delete(tstate);
  324.     PyInterpreterState_Delete(interp);
  325.  
  326.     return NULL;
  327. }
  328.  
  329. /* Delete an interpreter and its last thread.  This requires that the
  330.    given thread state is current, that the thread has no remaining
  331.    frames, and that it is its interpreter's only remaining thread.
  332.    It is a fatal error to violate these constraints.
  333.  
  334.    (Py_Finalize() doesn't have these constraints -- it zaps
  335.    everything, regardless.)
  336.  
  337.    Locking: as above.
  338.  
  339. */
  340.  
  341. void
  342. Py_EndInterpreter(tstate)
  343.     PyThreadState *tstate;
  344. {
  345.     PyInterpreterState *interp = tstate->interp;
  346.  
  347.     if (tstate != PyThreadState_Get())
  348.         Py_FatalError("Py_EndInterpreter: thread is not current");
  349.     if (tstate->frame != NULL)
  350.         Py_FatalError("Py_EndInterpreter: thread still has a frame");
  351.     if (tstate != interp->tstate_head || tstate->next != NULL)
  352.         Py_FatalError("Py_EndInterpreter: not the last thread");
  353.  
  354.     PyImport_Cleanup();
  355.     PyInterpreterState_Clear(interp);
  356.     PyThreadState_Swap(NULL);
  357.     PyInterpreterState_Delete(interp);
  358. }
  359.  
  360. static char *progname = "python";
  361.  
  362. void
  363. Py_SetProgramName(pn)
  364.     char *pn;
  365. {
  366.     if (pn && *pn)
  367.         progname = pn;
  368. }
  369.  
  370. char *
  371. Py_GetProgramName()
  372. {
  373.     return progname;
  374. }
  375.  
  376. static char *default_home = NULL;
  377.  
  378. void
  379. Py_SetPythonHome(home)
  380.     char *home;
  381. {
  382.     default_home = home;
  383. }
  384.  
  385. char *
  386. Py_GetPythonHome()
  387. {
  388.     char *home = default_home;
  389.     if (home == NULL)
  390.         home = getenv("PYTHONHOME");
  391.     return home;
  392. }
  393.  
  394. /* Create __main__ module */
  395.  
  396. static void
  397. initmain()
  398. {
  399.     PyObject *m, *d;
  400.     m = PyImport_AddModule("__main__");
  401.     if (m == NULL)
  402.         Py_FatalError("can't create __main__ module");
  403.     d = PyModule_GetDict(m);
  404.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  405.         PyObject *bimod = PyImport_ImportModule("__builtin__");
  406.         if (bimod == NULL ||
  407.             PyDict_SetItemString(d, "__builtins__", bimod) != 0)
  408.             Py_FatalError("can't add __builtins__ to __main__");
  409.         Py_DECREF(bimod);
  410.     }
  411. }
  412.  
  413. /* Import the site module (not into __main__ though) */
  414.  
  415. static void
  416. initsite()
  417. {
  418.     PyObject *m, *f;
  419.     m = PyImport_ImportModule("site");
  420.     if (m == NULL) {
  421.         f = PySys_GetObject("stderr");
  422.         if (Py_VerboseFlag) {
  423.             PyFile_WriteString(
  424.                 "'import site' failed; traceback:\n", f);
  425.             PyErr_Print();
  426.         }
  427.         else {
  428.             PyFile_WriteString(
  429.               "'import site' failed; use -v for traceback\n", f);
  430.             PyErr_Clear();
  431.         }
  432.     }
  433.     else {
  434.         Py_DECREF(m);
  435.     }
  436. }
  437.  
  438. /* Parse input from a file and execute it */
  439.  
  440. int
  441. PyRun_AnyFile(fp, filename)
  442.     FILE *fp;
  443.     char *filename;
  444. {
  445.     if (filename == NULL)
  446.         filename = "???";
  447.     if (Py_FdIsInteractive(fp, filename))
  448.         return PyRun_InteractiveLoop(fp, filename);
  449.     else
  450.         return PyRun_SimpleFile(fp, filename);
  451. }
  452.  
  453. int
  454. PyRun_InteractiveLoop(fp, filename)
  455.     FILE *fp;
  456.     char *filename;
  457. {
  458.     PyObject *v;
  459.     int ret;
  460.     v = PySys_GetObject("ps1");
  461.     if (v == NULL) {
  462.         PySys_SetObject("ps1", v = PyString_FromString(">>> "));
  463.         Py_XDECREF(v);
  464.     }
  465.     v = PySys_GetObject("ps2");
  466.     if (v == NULL) {
  467.         PySys_SetObject("ps2", v = PyString_FromString("... "));
  468.         Py_XDECREF(v);
  469.     }
  470.     for (;;) {
  471.         ret = PyRun_InteractiveOne(fp, filename);
  472. #ifdef Py_REF_DEBUG
  473.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  474. #endif
  475.         if (ret == E_EOF)
  476.             return 0;
  477.         /*
  478.         if (ret == E_NOMEM)
  479.             return -1;
  480.         */
  481.     }
  482. }
  483.  
  484. int
  485. PyRun_InteractiveOne(fp, filename)
  486.     FILE *fp;
  487.     char *filename;
  488. {
  489.     PyObject *m, *d, *v, *w;
  490.     node *n;
  491.     perrdetail err;
  492.     char *ps1 = "", *ps2 = "";
  493.     v = PySys_GetObject("ps1");
  494.     if (v != NULL) {
  495.         v = PyObject_Str(v);
  496.         if (v == NULL)
  497.             PyErr_Clear();
  498.         else if (PyString_Check(v))
  499.             ps1 = PyString_AsString(v);
  500.     }
  501.     w = PySys_GetObject("ps2");
  502.     if (w != NULL) {
  503.         w = PyObject_Str(w);
  504.         if (w == NULL)
  505.             PyErr_Clear();
  506.         else if (PyString_Check(w))
  507.             ps2 = PyString_AsString(w);
  508.     }
  509.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
  510.                    Py_single_input, ps1, ps2, &err);
  511.     Py_XDECREF(v);
  512.     Py_XDECREF(w);
  513.     if (n == NULL) {
  514.         if (err.error == E_EOF) {
  515.             if (err.text)
  516.                 PyMem_DEL(err.text);
  517.             return E_EOF;
  518.         }
  519.         err_input(&err);
  520.         PyErr_Print();
  521.         return err.error;
  522.     }
  523.     m = PyImport_AddModule("__main__");
  524.     if (m == NULL)
  525.         return -1;
  526.     d = PyModule_GetDict(m);
  527.     v = run_node(n, filename, d, d);
  528.     if (v == NULL) {
  529.         PyErr_Print();
  530.         return -1;
  531.     }
  532.     Py_DECREF(v);
  533.     if (Py_FlushLine())
  534.         PyErr_Clear();
  535.     return 0;
  536. }
  537.  
  538. int
  539. PyRun_SimpleFile(fp, filename)
  540.     FILE *fp;
  541.     char *filename;
  542. {
  543.     PyObject *m, *d, *v;
  544.     char *ext;
  545.  
  546.     m = PyImport_AddModule("__main__");
  547.     if (m == NULL)
  548.         return -1;
  549.     d = PyModule_GetDict(m);
  550.     ext = filename + strlen(filename) - 4;
  551. #ifdef _AMIGA
  552.     /* on Amiga, filenames are case insensitive */
  553.     if (stricmp(ext, ".pyc") == 0 || stricmp(ext, ".pyo") == 0
  554. #else
  555.     if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
  556. #endif /* _AMIGA */
  557. #ifdef macintosh
  558.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  559.         || getfiletype(filename) == 'PYC '
  560.         || getfiletype(filename) == 'APPL'
  561. #endif /* macintosh */
  562.         ) {
  563.         /* Try to run a pyc file. First, re-open in binary */
  564.         /* Don't close, done in main: fclose(fp); */
  565.         if( (fp = fopen(filename, "rb")) == NULL ) {
  566.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  567.             return -1;
  568.         }
  569.         /* Turn on optimization if a .pyo file is given */
  570.         if (strcmp(ext, ".pyo") == 0)
  571.             Py_OptimizeFlag = 1;
  572.         v = run_pyc_file(fp, filename, d, d);
  573.     } else {
  574.         v = PyRun_File(fp, filename, Py_file_input, d, d);
  575.     }
  576.     if (v == NULL) {
  577.         PyErr_Print();
  578.         return -1;
  579.     }
  580.     Py_DECREF(v);
  581.     if (Py_FlushLine())
  582.         PyErr_Clear();
  583.     return 0;
  584. }
  585.  
  586. int
  587. PyRun_SimpleString(command)
  588.     char *command;
  589. {
  590.     PyObject *m, *d, *v;
  591.     m = PyImport_AddModule("__main__");
  592.     if (m == NULL)
  593.         return -1;
  594.     d = PyModule_GetDict(m);
  595.     v = PyRun_String(command, Py_file_input, d, d);
  596.     if (v == NULL) {
  597.         PyErr_Print();
  598.         return -1;
  599.     }
  600.     Py_DECREF(v);
  601.     if (Py_FlushLine())
  602.         PyErr_Clear();
  603.     return 0;
  604. }
  605.  
  606. static int
  607. parse_syntax_error(err, message, filename, lineno, offset, text)
  608.      PyObject* err;
  609.      PyObject** message;
  610.      char** filename;
  611.      int* lineno;
  612.      int* offset;
  613.      char** text;
  614. {
  615.     long hold;
  616.     PyObject *v;
  617.  
  618.     /* old style errors */
  619.     if (PyTuple_Check(err))
  620.         return PyArg_Parse(err, "(O(ziiz))", message, filename,
  621.                    lineno, offset, text);
  622.  
  623.     /* new style errors.  `err' is an instance */
  624.  
  625.     if (! (v = PyObject_GetAttrString(err, "msg")))
  626.         goto finally;
  627.     *message = v;
  628.  
  629.     if (!(v = PyObject_GetAttrString(err, "filename")))
  630.         goto finally;
  631.     if (v == Py_None)
  632.         *filename = NULL;
  633.     else if (! (*filename = PyString_AsString(v)))
  634.         goto finally;
  635.  
  636.     Py_DECREF(v);
  637.     if (!(v = PyObject_GetAttrString(err, "lineno")))
  638.         goto finally;
  639.     hold = PyInt_AsLong(v);
  640.     Py_DECREF(v);
  641.     v = NULL;
  642.     if (hold < 0 && PyErr_Occurred())
  643.         goto finally;
  644.     *lineno = (int)hold;
  645.  
  646.     if (!(v = PyObject_GetAttrString(err, "offset")))
  647.         goto finally;
  648.     hold = PyInt_AsLong(v);
  649.     Py_DECREF(v);
  650.     v = NULL;
  651.     if (hold < 0 && PyErr_Occurred())
  652.         goto finally;
  653.     *offset = (int)hold;
  654.  
  655.     if (!(v = PyObject_GetAttrString(err, "text")))
  656.         goto finally;
  657.     if (v == Py_None)
  658.         *text = NULL;
  659.     else if (! (*text = PyString_AsString(v)))
  660.         goto finally;
  661.     Py_DECREF(v);
  662.     return 1;
  663.  
  664. finally:
  665.     Py_XDECREF(v);
  666.     return 0;
  667. }
  668.  
  669. void
  670. PyErr_Print()
  671. {
  672.     PyErr_PrintEx(1);
  673. }
  674.  
  675. void
  676. PyErr_PrintEx(set_sys_last_vars)
  677.     int set_sys_last_vars;
  678. {
  679.     int err = 0;
  680.     PyObject *exception, *v, *tb, *f;
  681.     PyErr_Fetch(&exception, &v, &tb);
  682.     PyErr_NormalizeException(&exception, &v, &tb);
  683.  
  684.     if (exception == NULL)
  685.         return;
  686.  
  687.     if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
  688.         if (Py_FlushLine())
  689.             PyErr_Clear();
  690.         fflush(stdout);
  691.         if (v == NULL || v == Py_None)
  692.             Py_Exit(0);
  693.         if (PyInstance_Check(v)) {
  694.             /* we expect the error code to be store in the
  695.                `code' attribute
  696.             */
  697.             PyObject *code = PyObject_GetAttrString(v, "code");
  698.             if (code) {
  699.                 Py_DECREF(v);
  700.                 v = code;
  701.                 if (v == Py_None)
  702.                     Py_Exit(0);
  703.             }
  704.             /* if we failed to dig out the "code" attribute,
  705.                then just let the else clause below print the
  706.                error
  707.             */
  708.         }
  709.         if (PyInt_Check(v))
  710.             Py_Exit((int)PyInt_AsLong(v));
  711.         else {
  712.             /* OK to use real stderr here */
  713.             PyObject_Print(v, stderr, Py_PRINT_RAW);
  714.             fprintf(stderr, "\n");
  715.             Py_Exit(1);
  716.         }
  717.     }
  718.     if (set_sys_last_vars) {
  719.         PySys_SetObject("last_type", exception);
  720.         PySys_SetObject("last_value", v);
  721.         PySys_SetObject("last_traceback", tb);
  722.     }
  723.     f = PySys_GetObject("stderr");
  724.     if (f == NULL)
  725.         fprintf(stderr, "lost sys.stderr\n");
  726.     else {
  727.         if (Py_FlushLine())
  728.             PyErr_Clear();
  729.         fflush(stdout);
  730.         err = PyTraceBack_Print(tb, f);
  731.         if (err == 0 &&
  732.             PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
  733.         {
  734.             PyObject *message;
  735.             char *filename, *text;
  736.             int lineno, offset;
  737.             if (!parse_syntax_error(v, &message, &filename,
  738.                         &lineno, &offset, &text))
  739.                 PyErr_Clear();
  740.             else {
  741.                 char buf[10];
  742.                 PyFile_WriteString("  File \"", f);
  743.                 if (filename == NULL)
  744.                     PyFile_WriteString("<string>", f);
  745.                 else
  746.                     PyFile_WriteString(filename, f);
  747.                 PyFile_WriteString("\", line ", f);
  748.                 sprintf(buf, "%d", lineno);
  749.                 PyFile_WriteString(buf, f);
  750.                 PyFile_WriteString("\n", f);
  751.                 if (text != NULL) {
  752.                     char *nl;
  753.                     if (offset > 0 &&
  754.                         offset == (int)strlen(text))
  755.                         offset--;
  756.                     for (;;) {
  757.                         nl = strchr(text, '\n');
  758.                         if (nl == NULL ||
  759.                             nl-text >= offset)
  760.                             break;
  761.                         offset -= (nl+1-text);
  762.                         text = nl+1;
  763.                     }
  764.                     while (*text == ' ' || *text == '\t') {
  765.                         text++;
  766.                         offset--;
  767.                     }
  768.                     PyFile_WriteString("    ", f);
  769.                     PyFile_WriteString(text, f);
  770.                     if (*text == '\0' ||
  771.                         text[strlen(text)-1] != '\n')
  772.                         PyFile_WriteString("\n", f);
  773.                     PyFile_WriteString("    ", f);
  774.                     offset--;
  775.                     while (offset > 0) {
  776.                         PyFile_WriteString(" ", f);
  777.                         offset--;
  778.                     }
  779.                     PyFile_WriteString("^\n", f);
  780.                 }
  781.                 Py_INCREF(message);
  782.                 Py_DECREF(v);
  783.                 v = message;
  784.                 /* Can't be bothered to check all those
  785.                    PyFile_WriteString() calls */
  786.                 if (PyErr_Occurred())
  787.                     err = -1;
  788.             }
  789.         }
  790.         if (err) {
  791.             /* Don't do anything else */
  792.         }
  793.         else if (PyClass_Check(exception)) {
  794.             PyClassObject* exc = (PyClassObject*)exception;
  795.             PyObject* className = exc->cl_name;
  796.             PyObject* moduleName =
  797.                   PyDict_GetItemString(exc->cl_dict, "__module__");
  798.  
  799.             if (moduleName == NULL)
  800.                 err = PyFile_WriteString("<unknown>", f);
  801.             else {
  802.                 char* modstr = PyString_AsString(moduleName);
  803.                 if (modstr && strcmp(modstr, "exceptions")) 
  804.                 {
  805.                     err = PyFile_WriteString(modstr, f);
  806.                     err += PyFile_WriteString(".", f);
  807.                 }
  808.             }
  809.             if (err == 0) {
  810.                 if (className == NULL)
  811.                       err = PyFile_WriteString("<unknown>", f);
  812.                 else
  813.                       err = PyFile_WriteObject(className, f,
  814.                                    Py_PRINT_RAW);
  815.             }
  816.         }
  817.         else
  818.             err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
  819.         if (err == 0) {
  820.             if (v != NULL && v != Py_None) {
  821.                 PyObject *s = PyObject_Str(v);
  822.                 /* only print colon if the str() of the
  823.                    object is not the empty string
  824.                 */
  825.                 if (s == NULL)
  826.                     err = -1;
  827.                 else if (!PyString_Check(s) ||
  828.                      PyString_GET_SIZE(s) != 0)
  829.                     err = PyFile_WriteString(": ", f);
  830.                 if (err == 0)
  831.                   err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
  832.                 Py_XDECREF(s);
  833.             }
  834.         }
  835.         if (err == 0)
  836.             err = PyFile_WriteString("\n", f);
  837.     }
  838.     Py_XDECREF(exception);
  839.     Py_XDECREF(v);
  840.     Py_XDECREF(tb);
  841.     /* If an error happened here, don't show it.
  842.        XXX This is wrong, but too many callers rely on this behavior. */
  843.     if (err != 0)
  844.         PyErr_Clear();
  845. }
  846.  
  847. PyObject *
  848. PyRun_String(str, start, globals, locals)
  849.     char *str;
  850.     int start;
  851.     PyObject *globals, *locals;
  852. {
  853.     return run_err_node(PyParser_SimpleParseString(str, start),
  854.                 "<string>", globals, locals);
  855. }
  856.  
  857. PyObject *
  858. PyRun_File(fp, filename, start, globals, locals)
  859.     FILE *fp;
  860.     char *filename;
  861.     int start;
  862.     PyObject *globals, *locals;
  863. {
  864.     return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
  865.                 filename, globals, locals);
  866. }
  867.  
  868. static PyObject *
  869. run_err_node(n, filename, globals, locals)
  870.     node *n;
  871.     char *filename;
  872.     PyObject *globals, *locals;
  873. {
  874.     if (n == NULL)
  875.         return  NULL;
  876.     return run_node(n, filename, globals, locals);
  877. }
  878.  
  879. static PyObject *
  880. run_node(n, filename, globals, locals)
  881.     node *n;
  882.     char *filename;
  883.     PyObject *globals, *locals;
  884. {
  885.     PyCodeObject *co;
  886.     PyObject *v;
  887.     co = PyNode_Compile(n, filename);
  888.     PyNode_Free(n);
  889.     if (co == NULL)
  890.         return NULL;
  891.     v = PyEval_EvalCode(co, globals, locals);
  892.     Py_DECREF(co);
  893.     return v;
  894. }
  895.  
  896. static PyObject *
  897. run_pyc_file(fp, filename, globals, locals)
  898.     FILE *fp;
  899.     char *filename;
  900.     PyObject *globals, *locals;
  901. {
  902.     PyCodeObject *co;
  903.     PyObject *v;
  904.     long magic;
  905.     long PyImport_GetMagicNumber();
  906.  
  907.     magic = PyMarshal_ReadLongFromFile(fp);
  908.     if (magic != PyImport_GetMagicNumber()) {
  909.         PyErr_SetString(PyExc_RuntimeError,
  910.                "Bad magic number in .pyc file");
  911.         return NULL;
  912.     }
  913.     (void) PyMarshal_ReadLongFromFile(fp);
  914.     v = PyMarshal_ReadObjectFromFile(fp);
  915.     fclose(fp);
  916.     if (v == NULL || !PyCode_Check(v)) {
  917.         Py_XDECREF(v);
  918.         PyErr_SetString(PyExc_RuntimeError,
  919.                "Bad code object in .pyc file");
  920.         return NULL;
  921.     }
  922.     co = (PyCodeObject *)v;
  923.     v = PyEval_EvalCode(co, globals, locals);
  924.     Py_DECREF(co);
  925.     return v;
  926. }
  927.  
  928. PyObject *
  929. Py_CompileString(str, filename, start)
  930.     char *str;
  931.     char *filename;
  932.     int start;
  933. {
  934.     node *n;
  935.     PyCodeObject *co;
  936.     n = PyParser_SimpleParseString(str, start);
  937.     if (n == NULL)
  938.         return NULL;
  939.     co = PyNode_Compile(n, filename);
  940.     PyNode_Free(n);
  941.     return (PyObject *)co;
  942. }
  943.  
  944. /* Simplified interface to parsefile -- return node or set exception */
  945.  
  946. node *
  947. PyParser_SimpleParseFile(fp, filename, start)
  948.     FILE *fp;
  949.     char *filename;
  950.     int start;
  951. {
  952.     node *n;
  953.     perrdetail err;
  954.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
  955.                 (char *)0, (char *)0, &err);
  956.     if (n == NULL)
  957.         err_input(&err);
  958.     return n;
  959. }
  960.  
  961. /* Simplified interface to parsestring -- return node or set exception */
  962.  
  963. node *
  964. PyParser_SimpleParseString(str, start)
  965.     char *str;
  966.     int start;
  967. {
  968.     node *n;
  969.     perrdetail err;
  970.     n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
  971.     if (n == NULL)
  972.         err_input(&err);
  973.     return n;
  974. }
  975.  
  976. /* Set the error appropriate to the given input error code (see errcode.h) */
  977.  
  978. static void
  979. err_input(err)
  980.     perrdetail *err;
  981. {
  982.     PyObject *v, *w;
  983.     char *msg = NULL;
  984.     v = Py_BuildValue("(ziiz)", err->filename,
  985.                 err->lineno, err->offset, err->text);
  986.     if (err->text != NULL) {
  987.         PyMem_DEL(err->text);
  988.         err->text = NULL;
  989.     }
  990.     switch (err->error) {
  991.     case E_SYNTAX:
  992.         msg = "invalid syntax";
  993.         break;
  994.     case E_TOKEN:
  995.         msg = "invalid token";
  996.         break;
  997.     case E_INTR:
  998.         PyErr_SetNone(PyExc_KeyboardInterrupt);
  999.         Py_XDECREF(v);
  1000.         return;
  1001.     case E_NOMEM:
  1002.         PyErr_NoMemory();
  1003.         Py_XDECREF(v);
  1004.         return;
  1005.     case E_EOF:
  1006.         msg = "unexpected EOF while parsing";
  1007.         break;
  1008.     case E_INDENT:
  1009.         msg = "inconsistent use of tabs and spaces in indentation";
  1010.         break;
  1011.     default:
  1012.         fprintf(stderr, "error=%d\n", err->error);
  1013.         msg = "unknown parsing error";
  1014.         break;
  1015.     }
  1016.     w = Py_BuildValue("(sO)", msg, v);
  1017.     Py_XDECREF(v);
  1018.     PyErr_SetObject(PyExc_SyntaxError, w);
  1019.     Py_XDECREF(w);
  1020. }
  1021.  
  1022. /* Print fatal error message and abort */
  1023.  
  1024. void
  1025. Py_FatalError(msg)
  1026.     char *msg;
  1027. {
  1028.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  1029. #ifdef macintosh
  1030.     for (;;);
  1031. #endif
  1032. #ifdef MS_WIN32
  1033.     OutputDebugString("Fatal Python error: ");
  1034.     OutputDebugString(msg);
  1035.     OutputDebugString("\n");
  1036. #ifdef _DEBUG
  1037.     DebugBreak();
  1038. #endif
  1039. #endif /* MS_WIN32 */
  1040.     abort();
  1041. }
  1042.  
  1043. /* Clean up and exit */
  1044.  
  1045. #ifdef WITH_THREAD
  1046. #include "pythread.h"
  1047. int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
  1048. #endif
  1049.  
  1050. #define NEXITFUNCS 32
  1051. static void (*exitfuncs[NEXITFUNCS])Py_PROTO((void));
  1052. static int nexitfuncs = 0;
  1053.  
  1054. int Py_AtExit(func)
  1055.     void (*func) Py_PROTO((void));
  1056. {
  1057.     if (nexitfuncs >= NEXITFUNCS)
  1058.         return -1;
  1059.     exitfuncs[nexitfuncs++] = func;
  1060.     return 0;
  1061. }
  1062.  
  1063. static void
  1064. call_sys_exitfunc()
  1065. {
  1066.     PyObject *exitfunc = PySys_GetObject("exitfunc");
  1067.  
  1068.     if (exitfunc) {
  1069.         PyObject *res, *f;
  1070.         Py_INCREF(exitfunc);
  1071.         PySys_SetObject("exitfunc", (PyObject *)NULL);
  1072.         f = PySys_GetObject("stderr");
  1073.         res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
  1074.         if (res == NULL) {
  1075.             if (f)
  1076.                 PyFile_WriteString("Error in sys.exitfunc:\n", f);
  1077.             PyErr_Print();
  1078.         }
  1079.         Py_DECREF(exitfunc);
  1080.     }
  1081.  
  1082.     if (Py_FlushLine())
  1083.         PyErr_Clear();
  1084. }
  1085.  
  1086. static void
  1087. call_ll_exitfuncs()
  1088. {
  1089.     while (nexitfuncs > 0)
  1090.         (*exitfuncs[--nexitfuncs])();
  1091.  
  1092.     fflush(stdout);
  1093.     fflush(stderr);
  1094. }
  1095.  
  1096. void
  1097. Py_Exit(sts)
  1098.     int sts;
  1099. {
  1100.     Py_Finalize();
  1101.  
  1102. #ifdef macintosh
  1103.     PyMac_Exit(sts);
  1104. #else
  1105.     exit(sts);
  1106. #endif
  1107. }
  1108.  
  1109. static void
  1110. initsigs()
  1111. {
  1112. #ifdef HAVE_SIGNAL_H
  1113. #ifdef SIGPIPE
  1114.     signal(SIGPIPE, SIG_IGN);
  1115. #endif
  1116. #endif /* HAVE_SIGNAL_H */
  1117.     PyOS_InitInterrupts(); /* May imply initsignal() */
  1118. }
  1119.  
  1120. #ifdef Py_TRACE_REFS
  1121. /* Ask a yes/no question */
  1122.  
  1123. int
  1124. _Py_AskYesNo(prompt)
  1125.     char *prompt;
  1126. {
  1127.     char buf[256];
  1128.     
  1129.     printf("%s [ny] ", prompt);
  1130.     if (fgets(buf, sizeof buf, stdin) == NULL)
  1131.         return 0;
  1132.     return buf[0] == 'y' || buf[0] == 'Y';
  1133. }
  1134. #endif
  1135.  
  1136. #ifdef MPW
  1137.  
  1138. /* Check for file descriptor connected to interactive device.
  1139.    Pretend that stdin is always interactive, other files never. */
  1140.  
  1141. int
  1142. isatty(fd)
  1143.     int fd;
  1144. {
  1145.     return fd == fileno(stdin);
  1146. }
  1147.  
  1148. #endif
  1149.  
  1150. /*
  1151.  * The file descriptor fd is considered ``interactive'' if either
  1152.  *   a) isatty(fd) is TRUE, or
  1153.  *   b) the -i flag was given, and the filename associated with
  1154.  *      the descriptor is NULL or "<stdin>" or "???".
  1155.  */
  1156. int
  1157. Py_FdIsInteractive(fp, filename)
  1158.     FILE *fp;
  1159.     char *filename;
  1160. {
  1161.     if (isatty((int)fileno(fp)))
  1162.         return 1;
  1163.     if (!Py_InteractiveFlag)
  1164.         return 0;
  1165.     return (filename == NULL) ||
  1166.            (strcmp(filename, "<stdin>") == 0) ||
  1167.            (strcmp(filename, "???") == 0);
  1168. }
  1169.